// 音乐API服务
import { API_CONFIG } from '../config/apiConfig';

export interface Song {
  pic: string;
  name: string;
  artist: string;
  rid: string;
  hash?: string;
}

export interface LyricResponse {
  status: number;
  info: string;
  errcode: number;
  errmsg: string;
  keyword: string;
  proposal: string;
  has_complete_right: number;
  companys: string;
  ugc: number;
  ugccount: number;
  expire: number;
  candidates: Array<{
    id: string;
    product_from: string;
    accesskey: string;
    can_score: boolean;
    singer: string;
    song: string;
    duration: number;
    uid: string;
    nickname: string;
    hitlayer: number;
    hitcasemask: number;
    adjust: number;
    score: number;
    contenttype: number;
    content_format: number;
    download_id: string;
  }>;
}

export interface LyricContentResponse {
  status: number;
  info: string;
  error_code: number;
  fmt: string;
  contenttype: number;
  _source: string;
  charset: string;
  content: string;
  id: string;
  decodeContent: string;
}

export interface TTMLResponse {
  message: string;
  mode: string;
  success: boolean;
  ttml_content: string;
}

export interface Comment {
  u_pic: string;
  u_name: string;
  msg: string;
}

export interface CommentResponse {
  rows: Comment[];
}

export interface AudioUrlResponse {
  data: {
    code: number;
    url: string;
  };
}

export interface SearchResponse {
  data: {
    list: Song[];
  };
}

class MusicApiService {
  private baseUrl = API_CONFIG.getBaseUrls();

  // 通用请求方法，包含错误处理
  private async request(url: string, options: RequestInit = {}): Promise<Response> {
    try {
      console.log('API Request:', url);
      const response = await fetch(url, {
        ...options,
        headers: {
          'Content-Type': 'application/json',
          ...options.headers,
        },
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      return response;
    } catch (error) {
      console.error('API Request failed:', url, error);
      throw error;
    }
  }

  // 搜索歌曲
  async searchSongs(keyword: string, page: number = 1): Promise<Song[]> {
    try {
      const response = await this.request(
        `${this.baseUrl.search}/search/searchMusicBykeyWord?key=${encodeURIComponent(keyword)}&pn=${page}`
      );
      const data: SearchResponse = await response.json();
      
      // 提取hash值并添加到Song对象中
      return data.data.list.map(song => ({
        ...song,
        hash: song.rid.split('-')[1] // 从rid中提取hash值
      }));
    } catch (error) {
      console.error('搜索歌曲失败:', error);
      return [];
    }
  }

  // 获取歌词信息
  async getLyricInfo(hash: string): Promise<{ id: string; accesskey: string } | null> {
    try {
      const response = await this.request(
        `${this.baseUrl.lyric}/search/lyric?hash=${hash}`
      );
      const data: LyricResponse = await response.json();
      
      if (data.status === 200 && data.candidates.length > 0) {
        const candidate = data.candidates[0];
        return {
          id: candidate.id,
          accesskey: candidate.accesskey
        };
      }
      return null;
    } catch (error) {
      console.error('获取歌词信息失败:', error);
      return null;
    }
  }

  // 获取歌词内容
  async getLyricContent(id: string, accesskey: string): Promise<string | null> {
    try {
      const response = await this.request(
        `${this.baseUrl.lyric}/lyric?id=${id}&accesskey=${accesskey}&fmt=krc&decode=true`
      );
      const data: LyricContentResponse = await response.json();
      
      if (data.status === 200) {
        return data.decodeContent;
      }
      return null;
    } catch (error) {
      console.error('获取歌词内容失败:', error);
      return null;
    }
  }

  // 转换歌词格式为TTML
  async convertToTTML(krcContent: string): Promise<string | null> {
    try {
      const response = await this.request(`${this.baseUrl.convert}/convert`, {
        method: 'POST',
        body: JSON.stringify({
          krc_content: krcContent,
          mode: 'word_improved'
        })
      });
      
      const data: TTMLResponse = await response.json();
      
      if (data.success) {
        return data.ttml_content;
      }
      return null;
    } catch (error) {
      console.error('转换歌词格式失败:', error);
      return null;
    }
  }

  // 获取完整的歌词（TTML格式）
  async getCompleteLyric(hash: string): Promise<string | null> {
    try {
      // 1. 获取歌词信息
      const lyricInfo = await this.getLyricInfo(hash);
      if (!lyricInfo) {
        console.log('未找到歌词信息');
        return null;
      }

      // 2. 获取KRC歌词内容
      const krcContent = await this.getLyricContent(lyricInfo.id, lyricInfo.accesskey);
      if (!krcContent) {
        console.log('未找到歌词内容');
        return null;
      }

      // 3. 转换为TTML格式
      const ttmlContent = await this.convertToTTML(krcContent);
      return ttmlContent;
    } catch (error) {
      console.error('获取完整歌词失败:', error);
      return null;
    }
  }

  // 获取评论
  async getComments(hash: string, page: number = 1, rows: number = 30): Promise<Comment[]> {
    try {
      // 生成随机sid前缀
      const randomPrefix = Math.floor(Math.random() * 999999);
      const sid = `${randomPrefix}-${hash}`;
      
      const response = await this.request(
        `${this.baseUrl.search}/comment?sid=${sid}&type=get_rec_comment&page=${page}&rows=${rows}&digest=15`
      );
      const data: CommentResponse = await response.json();
      
      return data.rows || [];
    } catch (error) {
      console.error('获取评论失败:', error);
      return [];
    }
  }

  // 获取音频链接
  async getAudioUrl(hash: string): Promise<string | null> {
    try {
      // 生成随机mid前缀
      const randomPrefix = Math.floor(Math.random() * 999999);
      const mid = `${randomPrefix}-${hash}`;
      
      const response = await this.request(
        `${this.baseUrl.search}/url?mid=${mid}`
      );
      const data: AudioUrlResponse = await response.json();
      
      if (data.data.code === 200) {
        return data.data.url;
      }
      return null;
    } catch (error) {
      console.error('获取音频链接失败:', error);
      return null;
    }
  }
}

export const musicApi = new MusicApiService();